package com.jichangxiu.framework.utils;

import cn.hutool.core.util.IdUtil;
import com.jichangxiu.common.constant.Constants;
import com.jichangxiu.common.constant.RedisConstants;
import com.jichangxiu.common.context.JcxContext;
import com.jichangxiu.common.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;

@Slf4j
public class RepeatUtils {

    public static Object setRepeatRequest(ProceedingJoinPoint proceedingJoinPoint, int second) throws Throwable {
        return repeatRequest(proceedingJoinPoint, JcxContext.getJti(), second);
    }

    private static Object repeatRequest(ProceedingJoinPoint proceedingJoinPoint, String jti, int second) throws Throwable {
        String clientId = IdUtil.randomUUID();
        String redisKey = RedisConstants.createRequestRepeatKey(Constants.JCX_PROPERTIES.getProjectName(), ServletUtils.getPath(), jti);
        boolean lock = LockUtils.lock(redisKey, clientId, second);
        if (lock) {
            Object object;
            try {
                long start = System.currentTimeMillis();
                object = proceedingJoinPoint.proceed();
                log.info("【RepeatUtils】业务耗时：" + (System.currentTimeMillis() - start));
            } finally {
                LockUtils.unlock(redisKey, clientId);
            }
            return object;
        } else {
            throw new RuntimeException("【RepeatUtils】操作过快");
        }
    }

}
